import _app = require('durandal/app');
import _ko = require('knockout');

import User = require('entities/user');
import Rating = require('entities/rating');

import DateHelper = require('lib/datehelper');

class QuestionInfo {
    public questionId: string;
    public questionKey: string;
    public points: Rating;
    public title: KnockoutProtectedObservable<string>;
    public abstract: KnockoutProtectedObservable<string>;
    public details: KnockoutProtectedObservable<string>;
    public argumentCount: number;
    public author: User;
    public tags: string[];
    public timeElapsed: string;
    public referredFrom: any[]; // Should be of ReferenceInfo type
    public refersTo: any[]; // Should be of ReferenceInfo type

    constructor(private _post: Disco.Ontology.Post) {
        this.questionId = _post.Id;
        this.questionKey = _post.Key;
        this.points = new Rating(_post.Ratings.map((rating => rating.Score)));
        this.title = _ko.protectedObservable<string>(_post.Content.Title || this.getIdentityDisplayString());
        this.abstract = _ko.protectedObservable<string>(_post.Content.Text || this.getIdentityDisplayString());
        this.details = _ko.protectedObservable<string>('');
        this.argumentCount = _post.ReferredFrom ? _post.ReferredFrom.length : 0;
        this.author = new User(_post.ModifiedBy.Author.Key, _post.ModifiedBy.Author.Alias);
        this.tags = []; 
        this.referredFrom = [];
        this.refersTo = [];
        this.timeElapsed = DateHelper.getTimeElapsed(_post.Modified);

        if (_post.Tags) {
            _post.Tags.forEach(tag => this.tags.push(tag.Description.Name));
        }
        if (_post.ReferredFrom) {
            _post.ReferredFrom.forEach(reference => this.referredFrom.push({
                id: reference.Id,
                referrerId: reference.ReferrerId
            }));
        }
        if (_post.RefersTo) {
            _post.RefersTo.forEach(reference => this.refersTo.push({
                id: reference.Id,
                referrerId: reference.ReferrerId // NOT NEEDED?!
            }));
        }
    }

    public reset(): void {
        for (var property in this) {
            if (this[property].reset) {
                this[property].reset();
            }
        }
    }

    public commit(): void {
        for (var property in this) {
            if (this[property].commit) {
                this[property].commit();
            }
        }
    }

    public getIdentityDisplayString(): string {
        return 'Post # ' + this.questionKey;
    }
}

export = QuestionInfo; 